package egean.pad.httpservice;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URLDecoder;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.provider.Settings;
import egean.pad.datacommunication.BaseActivity;
import egean.pad.datacommunication.MyApplication;
import egean.pad.tool.Common;
import egean.pad.tool.DataBaseAdapter;

public class HttpWebServer extends Thread {

	static final String SUFFIX_ZIP = "..zip";
	static final String SUFFIX_DEL = "..del";

	private int port;
	private String webRoot;
	public static boolean isLoop = false;
	private Context context;
	public static ServerSocket serverSocket = null;

	public static final String ACTION_LoginActivity = "com.android.httpservice.LoginAcitvity";
	public static final String ACTION_Dialog = "com.android.httpservice.Dialog";

	public HttpWebServer(int port, final String webRoot, Context context) {
		super();
		this.port = port;
		this.webRoot = webRoot;
		this.context = context;
	}

	@Override
	public void run() {
		try {
			// 创建服务器套接字
			serverSocket = new ServerSocket(port);
			/* 循环接收各客户端 */
			isLoop = true;
			while (isLoop) {
				// 接收客户端套接字
				Socket socket;
				InputStream inputStream;
				OutputStream outputStream;
				byte[] buf = new byte[1024];
				while (isLoop) {

					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					socket = serverSocket.accept();
					inputStream = socket.getInputStream();
					outputStream = socket.getOutputStream();
					String str = "";
					while (inputStream.read(buf, 0, buf.length) != -1) {
						 str = str+URLDecoder
								.decode(new String(buf), "UTF-8");
						str = str.trim();
						String[] _str = str.split(",");
						if("start".equals(_str[0]) && "end".equals(_str[_str.length-1])){
							if (DealData(str)) {
								outputStream.write("recv_ok".getBytes());
							} else {
								outputStream.write("recv_false".getBytes());
							}
							str = "";
						//开始结束都没有start，end字段则删除str内容
						}else if(!"start".equals(_str[0]) && !"end".equals(_str[_str.length-1])){
							str = "";
							outputStream.write("recv_false".getBytes());
						}else{
							outputStream.write("recv_false".getBytes());
						}
						// socket.getOutputStream().close();
						buf = new byte[1024];
					}
				}
			}
		} catch (IOException e) {
			// isLoop = false;
			e.printStackTrace();
		} finally {
			try {
				if (serverSocket != null) {
					serverSocket.close();
				}
			} catch (IOException e) {
			}
		}
	}

	/**
	 * 获取屏幕的亮度
	 * 
	 * @param activity
	 * @return
	 */
	public int getScreenBrightness(Context context) {
		int nowBrightnessValue = 0;
		ContentResolver resolver = context.getContentResolver();
		try {
			nowBrightnessValue = android.provider.Settings.System.getInt(
					resolver, Settings.System.SCREEN_BRIGHTNESS);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return nowBrightnessValue;
	}

	public void close() {
		// isLoop = false;
	}

	/**
	 * 处理原始数据
	 * 
	 * @param arr_str
	 */
	private boolean DealData(String str) {

		String[] arr_str = str.split(",");
		boolean flag = true;
		if (arr_str[0].equals("start")
				&& arr_str[arr_str.length - 1].equals("end")) {
			if (arr_str[1].equals("400")) {

				DataBaseAdapter datebase = new DataBaseAdapter(context);
				datebase.updateLoginedTOUnlogin();
				datebase.deleteChipIDInfoBYPN("-1");
				Cursor result = datebase.Select_PN_BY_Chip_ID(arr_str[2]);
				if(result == null){
					//-1表示该账户未注册或激活
					datebase.insertUserInfo("-1", "", "", "","", "", "", arr_str[2], "","", "", "", "", "", "", "", "unlogin","");
				}else{
					datebase.updateUnloginTOLogined(result.getString(result.getColumnIndex(DataBaseAdapter.DB_TABLE_USER_PN)));
				}
				datebase.close();
				// 芯片id
				context.sendBroadcast(Common.getIntentAction().putExtra("status", 0));

				// 解析血压数据
			}else if(arr_str[1].equals("404")){
				DataBaseAdapter datebase = new DataBaseAdapter(context);
				String user_info = arr_str[5];
				String user_name = user_info.substring(28, 88);
				user_name = Common.unicodeToString(user_name).trim();
				
				String user_sex = user_info.substring(88, 92);
				//男
				if("3100".equals(user_sex)){
					user_sex = "M";
				//女3200
				}else{
					user_sex = "F";
				}
				String user_ethnic = user_info.substring(92, 100);
				user_ethnic = Common.unicodeToString(user_ethnic);
				
				String user_birthday = user_info.substring(100, 132);
				user_birthday = Common.unicodeToString(user_birthday).trim();
				String day = user_birthday.substring(6,user_birthday.length());
				if(day.length() < 2){
					day = "0"+day;
				}
				user_birthday = user_birthday.substring(0, 4)+"/"+user_birthday.substring(4,6)+"/"+day;
				
				String user_address = user_info.substring(132, 272);
				user_address = Common.unicodeToString(user_address).trim();
				
				String user_idnumber = user_info.substring(272, 344);
				user_idnumber = Common.unicodeToString(user_idnumber).trim();

				datebase.updateLoginedTOUnlogin();
				datebase.deleteChipIDInfoBYPN("-1");
				Cursor result = datebase.Select_PN_BY_Chip_ID(arr_str[2]);
				if(result == null){
					//-1表示该账户未注册或激活
					datebase.insertUserInfo("-1", "", user_name, "","", "", user_idnumber, arr_str[2], "", user_birthday, "", "", "", user_sex, user_address, "", "unlogin","");
				}else{
					String pn = result.getString(result.getColumnIndex(DataBaseAdapter.DB_TABLE_USER_PN));
					datebase.updateUnloginTOLogined(pn);
				}
				datebase.close();
				context.sendBroadcast(Common.getIntentAction().putExtra("status", 2));
			} else {
				DealBPData(str);
			}
		} else {
			flag = false;
		}

		return flag;
	}
	/**
	 * 解析从数据通获取到的身份证数据
	 * 
	 * @param arr
	 */
	private void DealChipIDData(String str) {
		// start,401,guid,会员卡芯片ID或设备蓝牙MAC地址,高压，低压，心率，数据通MAC地址，血压计蓝牙MAC地址，血压计蓝牙名称,end
		// start,401,123131313123,123131313123,120,80,60,001122447755,001144557788,KYD-BP213,end
		context.sendBroadcast(new Intent(HttpWebServer.ACTION_Dialog).putExtra(
				"bpdata", str));
	}

	/**
	 * 解析从数据通获取到的数据
	 * 
	 * @param arr
	 */
	private void DealBPData(String str) {
		// start,401,guid,会员卡芯片ID或设备蓝牙MAC地址,高压，低压，心率，数据通MAC地址，血压计蓝牙MAC地址，血压计蓝牙名称,end
		// start,401,123131313123,123131313123,120,80,60,001122447755,001144557788,KYD-BP213,end
		context.sendBroadcast(new Intent(HttpWebServer.ACTION_Dialog).putExtra(
				"bpdata", str));
	}

}
